from typing import List, Optional
from datetime import timezone

from fastapi import APIRouter, HTTPException, Query
from sqlmodel import Session, select

from ..db import engine
from ..models import SessionLog
from ..schemas import LogSummary, LogDetail


router = APIRouter()


@router.get("/", response_model=List[LogSummary])
def list_logs(server_id: Optional[int] = Query(default=None)) -> List[LogSummary]:
    with Session(engine) as session:
        stmt = select(SessionLog)
        if server_id is not None:
            stmt = stmt.where(SessionLog.server_id == server_id)
        stmt = stmt.order_by(SessionLog.id.desc())
        rows = session.exec(stmt).all()
        return [
            LogSummary(
                id=r.id,
                server_id=r.server_id,
                started_at=(r.started_at if r.started_at.tzinfo else r.started_at.replace(tzinfo=timezone.utc)),
                ended_at=(r.ended_at if (r.ended_at is None or r.ended_at.tzinfo) else r.ended_at.replace(tzinfo=timezone.utc)),
                bytes_count=r.bytes_count,
            )
            for r in rows
        ]


@router.get("/{log_id}", response_model=LogDetail)
def get_log(log_id: int) -> LogDetail:
    with Session(engine) as session:
        row = session.get(SessionLog, log_id)
        if not row:
            raise HTTPException(status_code=404, detail="Log not found")
        return LogDetail(
            id=row.id,
            server_id=row.server_id,
            started_at=(row.started_at if row.started_at.tzinfo else row.started_at.replace(tzinfo=timezone.utc)),
            ended_at=(row.ended_at if (row.ended_at is None or row.ended_at.tzinfo) else row.ended_at.replace(tzinfo=timezone.utc)),
            bytes_count=row.bytes_count,
            content=row.content,
        )

